/*
 * This file is part of APNdroid.
 *
 * APNdroid is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * APNdroid is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with APNdroid. If not, see <http://www.gnu.org/licenses/>.
 */

package com.google.code.packetkiller;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;

import android.os.Handler;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.bluetooth.BluetoothAdapter;
import com.google.code.packetkiller.R;
import com.google.code.japndroid.IPacketKillCallbackListener;
import com.google.code.japndroid.IPacketKillService;
import com.google.code.japndroid.PacketKillerConstants;
import com.google.code.japndroid.PacketKillerUtils;
import com.google.code.packetkiller.ConnectivityHandler;
import com.google.code.packetkiller.Constants;
import com.google.code.packetkiller.Utils;
import com.google.code.packetkiller.dao.ConnectionDao;
import com.google.code.packetkiller.dao.DaoFactory;
import com.google.code.packetkiller.internal.AdSpecFactory;
import com.google.code.packetkiller.preferences.Prefs;
import com.google.code.packetkiller.preferences.SettingsActivity;

import android.widget.Button;
import android.content.DialogInterface;
/**
 * @author Martin Adamek <martin.adamek@gmail.com>
 */
public class MainActivity extends Activity {

    private static final int MENU_SETTINGS = 1;
    public static final int CHANGE_REQUEST = 1;
    
    private ConnectivityHandler mConnectivityHandler;

    //private TextView orientationText;
    private ImageView barOnOff;
	private SharedPreferences preference;
	
	
    static final float BRIGHTNESS_OFF = 0.00f;
    static final float BRIGHTNESS_MED = 0.50f;
    static final float BRIGHTNESS_MAX = 1.00f;
	

    static void updateIndicatorAndData(Context context, boolean enable, ImageView bar) {
        bar.setImageResource(enable ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        //todo it is better to use Utils method here because it contains extra logic for apn dao switcher
        ConnectionDao connectionDao = DaoFactory.getDao(context);
        connectionDao.setDataEnabled(enable);
        
        
        Utils.broadcastStatusChange(context, enable);
    }
    
    void updateIndicatorAndData2(Context context, boolean enable, ImageView bar) {
        bar.setImageResource(enable ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        //todo it is better to use Utils method here because it contains extra logic for apn dao switcher
        ConnectionDao connectionDao = DaoFactory.getDao(context);
        connectionDao.setDataEnabled(enable);
        
        
        //android.content.ContentResolver.setMasterSyncAutomatically(enable);
       
        Utils.broadcastStatusChange(context, enable);
        
		int pitch = Integer.parseInt(preference.getString("pref_orientation_value","0"));
        Utils.broadcastStatusChange(context, enable,pitch);
        
        if( enable ){
        	try {
				iPacketKillService.stop();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    }
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // give up any internal focus before we switch layouts
        final View focused = getCurrentFocus();
        if (focused != null) {
            focused.clearFocus();
        }

        setContentView(R.layout.main);

        // take care about data icon

        View indicatorData = findViewById(R.id.indicator_data);
        boolean isConnectedOrConnecting = Utils.isConnectedOrConnecting(this,false);

        // Set the initial resource for the bar image.
        final ImageView barOnOff = (ImageView) indicatorData.findViewById(R.id.bar_data_onoff);
        this.barOnOff = barOnOff;
        barOnOff.setImageResource(isConnectedOrConnecting ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);

        // Set the initial state of the clock "checkbox"
        final CheckBox dataOnOff = (CheckBox) indicatorData.findViewById(R.id.data_onoff);
        dataOnOff.setChecked(isConnectedOrConnecting);

        //TextView infoText = (TextView) findViewById(R.id.info_text);
        //TextView reconnectText = (TextView) findViewById(R.id.reconnect_text);
        //mConnectivityHandler = new ConnectivityHandler(this, infoText, reconnectText, barOnOff);
        mConnectivityHandler = new ConnectivityHandler(this, barOnOff);       
        // Clicking outside the "checkbox" should also change the state.

        indicatorData.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                dataOnOff.toggle();
                boolean enable = dataOnOff.isChecked();
                updateIndicatorAndData(getBaseContext(), enable, barOnOff);
            }
        });
        
        //orientationText = (TextView) findViewById(R.id.orientation_text);
        //orientationText.setText("dummy");
        
        /*
         * ################### Packet Killer ########################
         */
        // ================= WiFi Controll ================
        // Set the initial resource for the bar image.
        View indicatorWifi = findViewById(R.id.indicator_wifi);
        final ImageView barWifiOnOff = (ImageView) indicatorWifi.findViewById(R.id.bar_wifi_onoff);
        
        boolean isWifiConnectedOrConnecting = PacketKillerUtils.isWifiConnectedOrConnecting(this);
        barWifiOnOff.setImageResource(isWifiConnectedOrConnecting ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        final CheckBox wifiOnOff = (CheckBox) indicatorWifi.findViewById(R.id.wifi_onoff);
        wifiOnOff.setChecked(isWifiConnectedOrConnecting);
        indicatorWifi.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                wifiOnOff.toggle();
                boolean enable = wifiOnOff.isChecked();
                Intent message = new Intent(PacketKillerConstants.WIFI_STATUS_CHANGE_REQUEST);
                message.putExtra("enable",enable);
                getBaseContext().sendBroadcast(message);

                barWifiOnOff.setImageResource(enable ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
                // ON or OFF WiFi
                // broadcast onClickEvent
                //PacketKillerUtils.setEnableWifi(getBaseContext(),enable);
            }
        });
        
        // ================= BlueTooth Controll ================
        // Set the initial resource for the bar image.
        View indicatorBluetooth = findViewById(R.id.indicator_bluetooth);
        final ImageView barBluetoothOnOff = (ImageView) indicatorBluetooth.findViewById(R.id.bar_bluetooth_onoff);
        
        boolean isBluetoothActive = PacketKillerUtils.isBlueToothActive();
        barBluetoothOnOff.setImageResource(isBluetoothActive ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        final CheckBox bluetoothOnOff = (CheckBox) indicatorBluetooth.findViewById(R.id.bluetooth_onoff);
        bluetoothOnOff.setChecked(isBluetoothActive);
        if( PacketKillerUtils.canBlueToothAvailable() ){
        	indicatorBluetooth.setOnClickListener(new OnClickListener() {
        		public void onClick(View v) {
        			bluetoothOnOff.toggle();
        			boolean enable = bluetoothOnOff.isChecked();
        			String filter = BluetoothAdapter.ACTION_REQUEST_ENABLE;
        			if( ! enable ) {
        				filter = PacketKillerConstants.BLUETOOTH_REQUEST_DISENABLE;
        			}
        			Intent message = new Intent(filter);
        			//message.putExtra("enable",enable);
        			getBaseContext().sendBroadcast(message);
                
        			barBluetoothOnOff.setImageResource(enable ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
                // ON or OFF BlueTooth
                // broadcast onClickEvent
                // 
                // PacketKillerUtils.setEnableBlueTooth(enable);
        		}
        	});
        }
        
        // ====================== Brightness controll =============
        // 輝度調節が権限がなくて動作しないので、自動同期のON/OFFに変えてみる
        View indicatorBrightness = findViewById(R.id.indicator_brightness);
        final ImageView barBrightnessUpDown = (ImageView) indicatorBrightness.findViewById(R.id.bar_brightness_updown);
        //final WindowManager.LayoutParams lp = getWindow().getAttributes();
        //boolean isBrightnessUp = (lp.screenBrightness > 0.5f);
        boolean isBrightnessUp = android.content.ContentResolver.getMasterSyncAutomatically();
		Log.v("PACKET KILLER","MASTER SYNC AUTOMATICALLY (enable:" + isBrightnessUp + ")");
        barBrightnessUpDown.setImageResource(isBrightnessUp ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        
        
        final CheckBox brightnessUpDown = (CheckBox) indicatorBrightness.findViewById(R.id.brightness_updown);
        brightnessUpDown.setChecked(isBrightnessUp);
        indicatorBrightness.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                brightnessUpDown.toggle();

                boolean up = brightnessUpDown.isChecked();
                barBrightnessUpDown.setImageResource(up ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
                
    			Intent message = new Intent(PacketKillerConstants.MASTER_SYNCAUTOMATICALLY_CHANGE_REQUEST);
    			message.putExtra("enable",up);
    			getBaseContext().sendBroadcast(message);
/*
                Log.v("PACKET KILLER","BRIGHTNESS is " + lp.screenBrightness);
                if (lp != null) {
                    if( up ){
                    	lp.screenBrightness = 1.0f;
                    }else{
                    	lp.screenBrightness = 0.1f;
                    }
                    //getWindow().setAttributes(lp);
                }
                
                
                



				try {
					
					int val = Settings.System.getInt(getContentResolver() , Settings.System.SCREEN_BRIGHTNESS);
					Log.v("PACKET KILLER","BRIGHTNESS is " + val);
				} catch (SettingNotFoundException e) {
					Toast.makeText(getBaseContext(), "Error "+e.getMessage(), Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}

	        	int brightpref = 0; 
	        	if( up ){
	        		brightpref = 255;
	        	}else{
	        		brightpref = 5;

	        	}
	        	barBrightnessUpDown.setImageResource(up ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
	        	android.provider.Settings.System.putInt(getContentResolver(),"screen_brightness_mode",0);
	        	android.provider.Settings.System.putInt(getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, brightpref); 
	        	//Toast.makeText(getBaseContext(), "Brightness is  "+ brightpref, Toast.LENGTH_LONG).show();
                
                
                
                
    			Intent message = new Intent(PacketKillerConstants.DISPLAY_STATUS_CHANGE);
    			message.putExtra("screenBrightness",lp.screenBrightness);
    			getBaseContext().sendBroadcast(message);
    	   */
            }
        });
        /*
        SeekBar seekBar = (SeekBar) findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(seekbarListenser);
        seekBar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT);
        try {
        	mOldBrightness = Settings.System.getInt(getBaseContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (SettingNotFoundException snfe) {
        	mOldBrightness = MAXIMUM_BACKLIGHT;
        }
        seekBar.setProgress(mOldBrightness - MINIMUM_BACKLIGHT);
 		*/
        
        // ================= Task Killer ==============
        Button taskKillButton = (Button)findViewById(R.id.task_kill_all);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.kill_all_confirm);
        builder.setPositiveButton("OK",new DialogInterface.OnClickListener(){

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				// send kill all intent
                Intent message = new Intent(PacketKillerConstants.TASK_KILL_ALL_REQUEST);
                getBaseContext().sendBroadcast(message);
			}
        	
        });
        taskKillButton.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				//builder.setMessage()
				builder.create();
				builder.show();
			}
        	
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        preference = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        mConnectivityHandler.resume();
        
        refreshAll();
        
        // Set up GoogleAdView
        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);
        AdSpecFactory.create(this, mainLayout);
        
        Log.v("PACKET KILLER","ON RESUME ACTIVITY");
		packetKillServiceIntent = new Intent(IPacketKillService.class.getName());
		bindService(packetKillServiceIntent,conn,BIND_AUTO_CREATE);
		
		//orientationNotifyServiceIntent = new Intent(IOrientationNotifyService.class.getName());
		//bindService(orientationNotifyServiceIntent,conn2,BIND_AUTO_CREATE);
		

		Prefs prefs = new  Prefs(getBaseContext());
		if(! prefs.isLastStatusConnected() ){
            // broadcast onClickEvent
        	try {
        		if( iPacketKillService != null )
        				iPacketKillService.stop();
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            Intent message = new Intent(PacketKillerConstants.ON_RESUME);
            message.putExtra(Constants.STATUS_EXTRA, false);
    		int pitch = Integer.parseInt(preference.getString("pref_orientation_value","0"));
    		message.putExtra("pitch",pitch);
    		getBaseContext().sendBroadcast(message);
    		//Toast.makeText(this, "sendBroadcast to service " ,Toast.LENGTH_LONG).show();
		}
    }

    @Override
    protected void onPause() {
        super.onPause();
        
        mConnectivityHandler.pause();
        
        unbindService(conn);
        //unbindService(conn2);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_SETTINGS, 0, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences);
        return true;
    }

    /* Handles item selections */
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_SETTINGS:
            Intent i = new Intent(this, SettingsActivity.class);
            startActivity(i);
            return true;
        }
        return false;
    }


    private void refreshAll() {
    	mConnectivityHandler.refresh();  	
    	
        boolean isWifiConnectedOrConnecting = PacketKillerUtils.isWifiConnectedOrConnecting(this);
        View indicatorWifi = findViewById(R.id.indicator_wifi);
        final ImageView barWifiOnOff = (ImageView) indicatorWifi.findViewById(R.id.bar_wifi_onoff);
        barWifiOnOff.setImageResource(isWifiConnectedOrConnecting ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        
        View indicatorBluetooth = findViewById(R.id.indicator_bluetooth);
        final ImageView barBluetoothOnOff = (ImageView) indicatorBluetooth.findViewById(R.id.bar_bluetooth_onoff);
        boolean isBluetoothActive = PacketKillerUtils.isBlueToothActive();
        barBluetoothOnOff.setImageResource(isBluetoothActive ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        
        View indicatorBrightness = findViewById(R.id.indicator_brightness);
        final ImageView barBrightnessUpDown = (ImageView) indicatorBrightness.findViewById(R.id.bar_brightness_updown);
        
        //final WindowManager.LayoutParams lp = getWindow().getAttributes();
        //boolean isBrightnessUp = (lp.screenBrightness > 0.5f);
        boolean isBrightnessUp = android.content.ContentResolver.getMasterSyncAutomatically();
		//Log.v("PACKET KILLER","MASTER SYNC AUTOMATICALLY (enable:" + isBrightnessUp + ")");
        
        barBrightnessUpDown.setImageResource(isBrightnessUp ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        final CheckBox brightnessUpDown = (CheckBox) indicatorBrightness.findViewById(R.id.brightness_updown);
        brightnessUpDown.setChecked(isBrightnessUp);
    }
    
    
    // ======================== for packet killer ============================
    private Intent packetKillServiceIntent = null;

	private IPacketKillService iPacketKillService = null;

	private ServiceConnection conn = new ServiceConnection(){
		public void onServiceConnected(ComponentName name, IBinder service) {
			iPacketKillService = IPacketKillService.Stub.asInterface(service);
			try {
				iPacketKillService.addListener(listener);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		public void onServiceDisconnected(ComponentName name) {
			iPacketKillService = null;
		}
	};
	private Handler handler = new Handler(){
        @Override
		public void handleMessage(Message msg) {
        	boolean status = msg.getData().getBoolean("STATUS");
           	barOnOff.setImageResource(status? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off);
        	//refreshAll();
        	mConnectivityHandler.handleNetworkInfoInUI();
        	//Log.v("PACKET KILLER","REFRESH STATUS status is " + status);
        }
	};
    private IPacketKillCallbackListener listener = new IPacketKillCallbackListener.Stub(){
		public void refresh(boolean isEnabled) throws RemoteException {
 
			Context context = getBaseContext();
			Utils.broadcastStatusChange(context,isEnabled);
			Message message = new Message();
			Bundle bundle = new Bundle();
			bundle.putBoolean("STATUS",isEnabled);
			message.setData(bundle);
			handler.sendMessage(message);
		}
    };
}
